package com.spring.springboot.service;

import java.util.Date;
import java.util.UUID;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.springboot.entity.GoodInfoEntity;
import com.spring.springboot.jpa.GoodInfoRepository;
import com.spring.springboot.timer.GoodAddTimer;
import com.spring.springboot.timer.GoodStockCheckTimer;

/**
*@author LSY
*Time: 2018年12月21日上午10:32:34
*
*
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class GoodInfoService {

	@Autowired
	private Scheduler scheduler;
	@Autowired
	private GoodInfoRepository goodJPA;
	
	public Long saveGood(GoodInfoEntity goodInfo) throws Exception {
		
		goodJPA.save(goodInfo);
		
		//构建创建商品定时任务
        buildCreateGoodTimer();
        //构建商品库存定时任务
        buildGoodStockTimer();
		return goodInfo.getId();
		
	}
	
	/**
     * 构建创建商品定时任务
     */
	public void buildGoodStockTimer() throws Exception{
		//设置开始时间为1分钟之后
		long startTime = System.currentTimeMillis() + 1000 * 60;
		//任务名称
		String name = UUID.randomUUID().toString();
		//任务所属分组
		String groupName = GoodAddTimer.class.getName();
		//创建任务
		JobDetail jobDetail = JobBuilder.newJob(GoodAddTimer.class).withIdentity(name, groupName).build();
		//创建任务触发器
		Trigger trigger = TriggerBuilder.newTrigger().withIdentity(name, groupName).startAt(new Date(startTime)).build();
		scheduler.scheduleJob(jobDetail, trigger);
	}
	
	public void buildCreateGoodTimer() throws Exception {
		String name = UUID.randomUUID().toString();
		String group = GoodStockCheckTimer.class.getName();
		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/30 * * * * ?");
		JobDetail jobDetail = JobBuilder.newJob(GoodStockCheckTimer.class).withIdentity(name, group).build();
		Trigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group).withSchedule(scheduleBuilder).build();
		
		scheduler.scheduleJob(jobDetail, trigger);
	}
}
